package com.talkweb.citypickerview.style.citypickerview.widget.wheel;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Picker;
import ohos.app.Context;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 滚动选择器  T类需采用注解(PickerData)配置显示的String数据
 */
public class WheelPicker<T> extends Picker {

    private List<T> mList = new ArrayList<>();

    public void setDisplayedData(List<T> list) {
        //注解方式注入
        if (list == null || list.size() == 0) {
            return;
        }

        mList.clear();
        mList.addAll(list);

        T t = list.get(0);
        Field[] fields = t.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return;
        }

        List<String> datas = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < fields.length; j++) {
                Field field = fields[j];
                PickerData annotation = field.getAnnotation(PickerData.class);
                if (annotation != null) {
                    Class<?> type = field.getType();
                    if (type.isAssignableFrom(String.class)){
                        //滚动显示str内容
                        try {
                            field.setAccessible(true);
                            Object obj = field.get(list.get(i));
                            if (obj instanceof String) {
                                datas.add((String) obj);
                            }
                            break;
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }

        setDisplayedData(datas.toArray(new String[]{}));
    }

    public WheelPicker(Context context) {
        super(context);
    }

    public WheelPicker(Context context, AttrSet attrSet) {
        super(context, attrSet);
    }

    public WheelPicker(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

}
